<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title> 家計簿　</title>
<!--[if IE]><script type="text/javascript" src="js/excanvas.js"></script><![endif]-->
    <script type="text/javascript" src="js/line.js"></script>
    <script type="text/javascript" src="js/prototype-1.6.0.3.js"></script>
    <script type="text/javascript" src="js/dateselect.js"></script>
    <script type="text/javascript" src="js/category.js"></script>
    <script type="text/javascript" src="js/common.js"></script>
    <link href="css/account.css" rel="stylesheet" type="text/css">
    <link rel="shortcut icon" href="favicon.ico">
  </head>
<body>
  {% include "_menu.html" %}
  <form id="account" action="/viewgraph" method="get">
    <div id="line_graph">
      <span class="bold">表示間隔</span>
      <input type="radio" id="month" name="type" value="month" onclick="javascript:changeInput();" checked="checked">
      月単位
      </input>
      <input type="radio" id="day" name="type" value="day" onclick="javascript:changeInput();">日単位</input>
      <div id="from_date">開始日(14日間)</div>
      <div id="from_month">開始月(13ヶ月間)</div>
    </div>
    <input type="submit" style="margin-top:10px;" value="グラフ表示" onclick="dataSend(); return false;"/>
  </form>
  <span class="title" id="items_span"></span>
  <div id="container_graph">
    <canvas id="graph_canvas" width="800" height="600"></canvas>
  </div>
  <script type="text/javascript">
    var categoryData= null;
    var accountArray = null;
    var gCanvas = null;
    function dataSend()
    {
      var json=null;
      var url = null;
      var callBack = null;
      $('items_span').innerHTML="";
      $('container_graph').childElements().each(function(n){if(n.id=="graph_canvas"){return;}n.remove();});
      gCanvas = new html5jp.graph.line("graph_canvas");
      url = '/lineGraph.json';
      callBack = makeLineGraph;
      var a = new Ajax.Request( 
          url,
          { 
              "method": "get", 
              "parameters": Form.serialize('account') + "&" + makeTemporaryQuery(),
              "sanitizeJSON":true,
              onSuccess: function(request) { 
                var clean = request.responseText.gsub(/</,"&lt;").gsub(/>/,"&gt;").gsub(/'/,"&apos;");
                var dataSet = clean.evalJSON(true);
                callBack(dataSet);
              }, 
              onFailure: function(request) { 
                  alert('読み込みに失敗しました'); 
              }, 
              onException: function (request) { 
                  alert('読み込み中にエラーが発生しました'); 
              } 
          } 
      ); 
    }
    function extractCategory(accountData)
    {
        var categoryName = {};
        var categoryNameArray = new Array();
        for(ac in accountData)
        {
            for(acName in accountData[ac])
            {
                if(! categoryName[acName])
                {
                    categoryName[acName]= true;
                    categoryNameArray.push(acName);
                }
            }
        }
        return categoryNameArray;
    }
    function dateSort(a,b){
      var aArr = a.split("/");
      var bArr = b.split("/");
      var aMonth = parseInt(aArr[0],10);
      var bMonth = parseInt(bArr[0],10);

      if(aMonth == 12 && bMonth == 1)
      {
        return -1;
      }
      else if(bMonth == 12 && aMonth == 1)
      {
        return 1;

      }else if(aMonth < bMonth)
      {
        return -1;

      }else if (aMonth > bMonth)
      {
        return 1;
      }
      else if(parseInt(aArr[1],10) < parseInt(bArr[1],10))
      {
        return -1;
      }else if(parseInt(aArr[1],10) > parseInt(bArr[1],10))
      {
        return 1;
      }
      return 0;
    }
    function accountFormatData(accountData,categories)
    {
        var dayArray = new Array();
        var dataSet = new Array();
        for(ac in accountData)
        {
          if(accountData[ac] != 0)
          {
            dayArray.push(ac);
          }
        }
        sortDate = dayArray.sort(dateSort);
        for(var i=0;i<sortDate.length;i++)
        {
            var total = 0;
            var caDatas = accountData[sortDate[i]];
            var acData = {};
            for( caData in caDatas)
            {
                acData[caData] = caDatas[caData];
                total +=  caDatas[caData];
            }
            for(var j=0;j<categories.length;j++)
            {
                if(typeof caDatas[categories[j]] == 'undefined')
                {
                    acData[categories[j]]=0;
                }
            }
            acData["すべて"]=total;
            dataSet.push({"date":sortDate[i],"categoryData":acData});
        }
        return dataSet;
    }
    function dispLineGraph()
    {
        $('container_graph').childElements().each(function(n){if(n.id=="graph_canvas"){return;}n.remove();});
        var categoryArray = new Array();
        $$('#items_span input').each(function(s,index)
        {
            if(s.checked)
            {
                categoryArray.push(s.value);
            }
        });
        dispLine(categoryArray);
    }
    function dispLine(categoryArray)
    {
        var dayArray = ["日付"];
        var categoryHash = {};
        for(var i=0;i<categoryArray.length;i++)
        {
            categoryHash[categoryArray[i]] = [categoryArray[i]];
        }

        for(var i=0;i<accountArray.length;i++)
        { 
            dayArray.push(accountArray[i].date);
            var categoriesData = accountArray[i].categoryData;
            for(var j=0;j<categoryArray.length;j++)
            {
                cData = categoriesData[categoryArray[j]];
                categoryHash[categoryArray[j]].push(cData);
            }
        }
        var categoryDataArray = new Array();
        for(c in categoryHash)
        {
            categoryDataArray.push(categoryHash[c]);
        }
        gCanvas.draw(categoryDataArray,{"x":dayArray});
    }
    function makeLineGraph(accountData)
    {
        var categories = extractCategory(accountData);
        if(categories.length==0)
        {
          alert("表示できるデータがありません。");
          return;
        }
        accountArray = accountFormatData(accountData,categories);
        var elemStr = "";
        for(var i=0;i<categories.length;i++)
        {
            elemStr += '<input type="checkbox" id="chk_'+i+'" onclick="dispLineGraph()" value="'+
                categories[i]+'">'+ categories[i]+'</input>';
        }
        elemStr += '<input type="checkbox" id="chk_'+ categories.length + 
            '" onclick="dispLineGraph()" checked="checked" value="すべて">すべて</input>';
        $('items_span').update(elemStr); 
        dispLineGraph();
    }
    function changeInput(type)
    {
      if($('month').checked){
        $('from_date').hide();
        $('from_month').show();
      }
      else if($('day').checked)
      {
        $('from_month').hide();
        $('from_date').show();
      }
    }
    window.onload = function() {
      var dateObj = new Date();
      var fromDaySelector = new DateSelector('day','from_date',null,dateObj.getFullYear(),dateObj.getMonth()+1,
          dateObj.getDate()-13);
      var fromMonthSelector = new DateSelector('month','from_month',null,dateObj.getFullYear()-1,dateObj.getMonth()+1,1);
      $('month_day_span').hide();
      $('month_weekday_span').hide();
      changeInput();
    };
  </script>
</body>
</html>
